import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import {
  getAdList,
  createAd,
  updateAd,
  deleteAd,
  updateAdStatus,
  batchDeleteAd,
  publishAd,
  unpublishAd,
  getAdPositionList
} from "@/api/ad";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { deviceDetection } from "@pureadmin/utils";
import type { FormItemProps, AdPositionProps } from "../utils/types";
import {
  AdStatus,
  AdType,
  AdStatusText,
  AdTypeText,
  adStatusOptions,
  adTypeOptions,
  getAdStatusTagType,
  calculateClickRate
} from "../utils/types";
import { useAdHook } from "../hooks";

export function useAd() {
  const form = reactive({
    name: "",
    positionId: null,
    type: null,
    status: null,
    advertiser: "",
    startTime: "",
    endTime: "",
    createTime: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const positionList = ref<AdPositionProps[]>([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle, tagStyle, getStatusTagType, getTypeTagType } = useAdHook();
  const { tagStyle: publicTagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号")
    },
    {
      label: "广告名称",
      prop: "name",
      minWidth: 150,
      cellRenderer: ({ row, props }) => (
        <el-link
          class="no-pager"
          size={props.size}
          type="primary"
          underline={false}
          style={{
            fontSize: props.size === "small" ? "12px" : "14px",
            marginRight: "4px"
          }}
          onClick={() => openDialog("查看", row)}
        >
          {row.name}
        </el-link>
      )
    },
    {
      label: "广告位",
      prop: "positionName",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <el-tag size="small" type="primary">
          {row.positionName}
        </el-tag>
      )
    },
    {
      label: "广告类型",
      prop: "type",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size === "small" ? "small" : "default"}
          type={getTypeTagType(row.type)}
        >
          {AdTypeText[row.type]}
        </el-tag>
      )
    },
    {
      label: "广告图片",
      prop: "imageUrl",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        row.imageUrl ? (
          <el-image
            style="width: 60px; height: 40px"
            src={row.imageUrl}
            preview-src-list={[row.imageUrl]}
            fit="cover"
          />
        ) : (
          <span class="text-gray-400">无图片</span>
        )
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size === "small" ? "small" : "default"}
          type={getAdStatusTagType(row.status)}
          style={tagStyle.value(row.status)}
        >
          {AdStatusText[row.status]}
        </el-tag>
      )
    },
    {
      label: "广告主",
      prop: "advertiser",
      minWidth: 120
    },
    {
      label: "投放时间",
      prop: "duration",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <div class="text-sm">
          <div>开始：{row.startTime ? dayjs(row.startTime).format("YYYY-MM-DD") : "未设置"}</div>
          <div>结束：{row.endTime ? dayjs(row.endTime).format("YYYY-MM-DD") : "未设置"}</div>
        </div>
      )
    },
    {
      label: "展示/点击",
      prop: "statistics",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <div class="text-sm">
          <div>展示：{row.viewCount || 0}</div>
          <div>点击：{row.clickCount || 0}</div>
          <div class="text-primary">率：{calculateClickRate(row.clickCount || 0, row.viewCount || 0)}</div>
        </div>
      )
    },
    {
      label: "预算/消费",
      prop: "budget",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <div class="text-sm">
          <div>预算：¥{row.budget || 0}</div>
          <div>消费：¥{row.spent || 0}</div>
        </div>
      )
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 80
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 180,
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const buttonClass = [
    "!h-[20px]",
    "reset-margin",
    "!text-gray-500",
    "dark:!text-white",
    "dark:hover:!text-primary"
  ];

  // 生成模拟广告位数据
  function generateMockPositions(): AdPositionProps[] {
    return [
      { id: 1, name: "首页横幅", code: "home_banner", type: 1, status: 1, sort: 1 },
      { id: 2, name: "侧边栏广告", code: "sidebar_ad", type: 2, status: 1, sort: 2 },
      { id: 3, name: "内容页广告", code: "content_ad", type: 5, status: 1, sort: 3 },
      { id: 4, name: "弹窗广告", code: "popup_ad", type: 3, status: 0, sort: 4 },
      { id: 5, name: "浮动广告", code: "floating_ad", type: 4, status: 1, sort: 5 }
    ];
  }

  // 生成模拟数据
  function generateMockData(count: number = 20): FormItemProps[] {
    const mockData: FormItemProps[] = [];
    const names = [
      "乒乓球拍促销广告",
      "世界杯赛事推广",
      "俱乐部招生广告",
      "培训课程宣传",
      "装备品牌推广",
      "赛事直播广告",
      "会员优惠活动",
      "新品发布宣传"
    ];
    const advertisers = ["红双喜", "蝴蝶", "斯蒂卡", "亚萨卡", "银河", "729"];
    const positions = generateMockPositions();

    for (let i = 0; i < count; i++) {
      const randomName = names[Math.floor(Math.random() * names.length)];
      const randomAdvertiser = advertisers[Math.floor(Math.random() * advertisers.length)];
      const randomPosition = positions[Math.floor(Math.random() * positions.length)];
      const randomStatus = Math.floor(Math.random() * 4);
      const randomType = Math.floor(Math.random() * 4) + 1;
      const viewCount = Math.floor(Math.random() * 10000) + 1000;
      const clickCount = Math.floor(Math.random() * viewCount * 0.1);
      const budget = Math.floor(Math.random() * 50000) + 10000;
      const spent = Math.floor(Math.random() * budget * 0.8);
      
      mockData.push({
        id: i + 1,
        name: `${randomName} ${i + 1}`,
        positionId: randomPosition.id,
        positionName: randomPosition.name,
        type: randomType,
        title: `广告标题 ${i + 1}`,
        description: `这是第${i + 1}个广告的描述信息`,
        imageUrl: `https://picsum.photos/400/300?random=${i}`,
        linkUrl: `https://example.com/ad/${i + 1}`,
        status: randomStatus,
        startTime: dayjs().subtract(Math.floor(Math.random() * 30), "day").format("YYYY-MM-DD HH:mm:ss"),
        endTime: dayjs().add(Math.floor(Math.random() * 60), "day").format("YYYY-MM-DD HH:mm:ss"),
        sort: Math.floor(Math.random() * 100),
        clickCount,
        viewCount,
        clickRate: calculateClickRate(clickCount, viewCount),
        advertiser: randomAdvertiser,
        budget,
        spent,
        createTime: dayjs().subtract(Math.floor(Math.random() * 60), "day").format("YYYY-MM-DD HH:mm:ss"),
        updateTime: dayjs().subtract(Math.floor(Math.random() * 10), "day").format("YYYY-MM-DD HH:mm:ss"),
        remark: `备注信息${i + 1}`
      });
    }
    return mockData;
  }

  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除广告"${row.name}"吗？`,
      "删除确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        await deleteAd(row.id);
        message("删除成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleBatchDelete(val) {
    if (val.length === 0) {
      message("请选择要删除的数据", { type: "warning" });
      return;
    }
    ElMessageBox.confirm(
      `确认要删除选中的 ${val.length} 条广告吗？`,
      "批量删除确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        const ids = val.map(item => item.id);
        await batchDeleteAd(ids);
        message("批量删除成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    try {
      // 模拟API调用
      const mockData = generateMockData(50);
      
      // 模拟搜索过滤
      let filteredData = mockData;
      if (form.name) {
        filteredData = filteredData.filter(item => 
          item.name.toLowerCase().includes(form.name.toLowerCase())
        );
      }
      if (form.positionId !== null && form.positionId !== "") {
        filteredData = filteredData.filter(item => item.positionId === form.positionId);
      }
      if (form.type !== null && form.type !== "") {
        filteredData = filteredData.filter(item => item.type === form.type);
      }
      if (form.status !== null && form.status !== "") {
        filteredData = filteredData.filter(item => item.status === form.status);
      }
      if (form.advertiser) {
        filteredData = filteredData.filter(item => 
          item.advertiser?.toLowerCase().includes(form.advertiser.toLowerCase())
        );
      }
      
      // 模拟分页
      const total = filteredData.length;
      const start = (pagination.currentPage - 1) * pagination.pageSize;
      const end = start + pagination.pageSize;
      const pageData = filteredData.slice(start, end);
      
      dataList.value = pageData;
      pagination.total = total;
    } catch (error) {
      console.error("获取广告列表失败:", error);
      message("获取广告列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}广告`,
      props: {
        formInline: {
          id: row?.id ?? null,
          name: row?.name ?? "",
          positionId: row?.positionId ?? null,
          type: row?.type ?? AdType.IMAGE,
          title: row?.title ?? "",
          description: row?.description ?? "",
          imageUrl: row?.imageUrl ?? "",
          linkUrl: row?.linkUrl ?? "",
          status: row?.status ?? AdStatus.DRAFT,
          startTime: row?.startTime ?? "",
          endTime: row?.endTime ?? "",
          sort: row?.sort ?? 0,
          advertiser: row?.advertiser ?? "",
          budget: row?.budget ?? 0,
          remark: row?.remark ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了广告名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 实际开发中这里会调用新增和编辑接口
            chores();
          }
        });
      }
    });
  }

  async function handlePublish(row) {
    try {
      await publishAd(row.id);
      message("广告上线成功", { type: "success" });
      onSearch();
    } catch (error) {
      message("广告上线失败", { type: "error" });
    }
  }

  async function handleUnpublish(row) {
    try {
      await unpublishAd(row.id);
      message("广告下线成功", { type: "success" });
      onSearch();
    } catch (error) {
      message("广告下线失败", { type: "error" });
    }
  }

  // 获取广告位列表
  async function loadPositions() {
    try {
      // 使用模拟数据
      positionList.value = generateMockPositions();
    } catch (error) {
      console.error("获取广告位列表失败:", error);
    }
  }

  onMounted(() => {
    onSearch();
    loadPositions();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    positionList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleBatchDelete,
    handlePublish,
    handleUnpublish,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}